package cn.ihna.component.mybatis;

import java.util.List;
import java.util.Properties;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;

/**
 * @author 京程(xianyingda)
 * @date 2021/03/04
 * @time 11:18 AM
 */
public class LombokModelPlugin extends PluginAdapter {

    public boolean validate(List<String> warnings) {
        // this plugin is always valid
        return true;
    }

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);
    }

    @Override
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        interfaze.addAnnotation("@org.springframework.stereotype.Component");
        return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,
        IntrospectedTable introspectedTable) {
        makeData(topLevelClass, introspectedTable);
        return true;
    }

    @Override
    public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass,
        IntrospectedTable introspectedTable) {
        makeData(topLevelClass, introspectedTable);
        return true;
    }

    @Override
    public boolean modelRecordWithBLOBsClassGenerated(
        TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        makeData(topLevelClass, introspectedTable);
        return true;
    }

    protected void makeData(TopLevelClass topLevelClass,
        IntrospectedTable introspectedTable) {
        topLevelClass.addAnnotation("@lombok.Data");
        List<Field> fields = topLevelClass.getFields();
        FullyQualifiedJavaType LDTtype = new FullyQualifiedJavaType("java.time.LocalDateTime");
        for (Field field : fields) {
            FullyQualifiedJavaType type = field.getType();
            String fullyQualifiedName = type.getFullyQualifiedName();
            if (fullyQualifiedName.equals("java.util.Date")) {
                field.setType(LDTtype);
            }
        }
        List<Method> methods = topLevelClass.getMethods();
        methods.clear();
    }
}
